package com.tools.service;

import com.tools.security.utils.SecurityCacheKeyUtils;
import com.tools.commons.cache.AbstractStringCacheStore;
import com.tools.commons.utils.StringUtils;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.awt.*;
import java.util.concurrent.TimeUnit;

@Service
@RequiredArgsConstructor
public class CaptchaServiceImpl implements CaptchaService {
    private final AbstractStringCacheStore cacheStore;

    @Override
    public String generator(String uid) {
        // 三个参数分别为宽、高、位数
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 5);
        // 设置字体
        specCaptcha.setFont(new Font("Verdana", Font.PLAIN, 32));  // 有默认字体，可以不用设置
        // 设置类型，纯数字、纯字母、字母数字混合
        specCaptcha.setCharType(Captcha.TYPE_ONLY_NUMBER);
        cacheStore.putIfAbsent(
                SecurityCacheKeyUtils.buildUserIdCaptcha(uid),
                specCaptcha.text(),
                60,
                TimeUnit.SECONDS
        );
        return specCaptcha.toBase64();
    }

    @Override
    public boolean validCaptcha(String captchaKey, String inputCaptcha) {
        return StringUtils.equals(inputCaptcha, getCacheCaptcha(captchaKey));
    }

    @Override
    public String getCacheCaptcha(String captchaKey) {
        String result = null;
        if (StringUtils.isNotBlank(captchaKey)) {
            String key = SecurityCacheKeyUtils.buildUserIdCaptcha(captchaKey);
            result = cacheStore.get(key).orElse(null);
            cacheStore.delete(key);
        }
        return result;
    }
}
